<template>
  <div>
    <el-dialog
      class="customer-dialog"
      v-model="dialogVisible"
      :title="!dialogParam.title ? '弹出框' : dialogParam.title"
      :destroy-on-close="true"
      @close="handleCancel"
    >
      <div>
        <el-row class="dialog-style">
          <el-col
            :span="props.dialogParam.multiple ? 16 : 24"
            class="dialog-style-left"
          >
            <!-- <el-col :span="16" class="dialog-style-left"> -->
            <el-radio-group
              v-if="dialogObj.tabShow"
              v-model="tabVal"
              @change="changeTab"
              class="flex justify-between items-center w-full"
            >
              <template v-for="(item, index) in tabList" :key="index">
                <el-radio-button
                  :label="item.name"
                  :style="{ width: radioBtnWidth }"
                  >{{ item.label }}</el-radio-button
                >
              </template>
            </el-radio-group>

            <div v-show="tabVal == 'customer'">
              <!-- <el-select
              v-model="customerId"
              placeholder="请输入客户名称选择客户"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              filterable
              remote
              :multiple="dialogObj.multiple"
              :checkStrictly="dialogObj.checkStrictly"
              :remote-method="val => queryCustomer(val)"
              :loading="loadingSelect"
              no-data-text="未查询到客户"
            >
              <el-option
                v-for="item in parentOptions"
                :key="item.id"
                :label="item.customerName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.customerName }}</span>
                  <span v-if="item.mainContactName"
                    >({{ item.mainContactName }})</span
                  >
                </div>
              </el-option>
            </el-select> -->
              <el-tabs
                v-model="customerQuery.customerCondition"
                class="text-base"
              >
                <el-tab-pane
                  v-for="(item, index) in customer_condition"
                  :key="index"
                  :label="item.label"
                  :name="item.value"
                />
              </el-tabs>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-input
                    size="small"
                    v-model="customerQuery.customer"
                    class="w-full"
                    placeholder="客户名称"
                    :prefix-icon="'Search'"
                    clearable
                    @change="getCustomerList"
                  />
                </el-col>
                <el-col :span="8">
                  <el-input
                    size="small"
                    v-model="customerQuery.customerTaxcode"
                    class="w-full"
                    placeholder="客户税号"
                    :prefix-icon="'Search'"
                    clearable
                    @change="getCustomerList"
                  />
                </el-col>
                <el-col :span="8">
                  <el-select
                    size="small"
                    v-model="customerQuery.customerType"
                    placeholder="选择客户类别"
                    class="w-full"
                    clearable
                    @change="getCustomerList"
                  >
                    <el-option
                      v-for="(dict, index) in customer_class"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <div class="list mt-6" v-loading="loading.customer">
                <div class="overflow-y-auto" id="customerBox">
                  <div
                    v-for="(item, index) in customerList"
                    :key="index"
                    :class="[
                      'list-row',
                      'cursor-pointer',
                      'border-solid',
                      'border-1',
                      'border-gray-200',
                      'px-4',
                      'pb-4',
                      'flex',
                      'items-center',
                      'shadow-md',
                      'mb-4',
                      rowCalss(item)
                    ]"
                    @click="clickRow(item)"
                  >
                    <div>
                      <!-- <span :class="checkIcon(item)"></span> -->
                      <!-- <el-checkbox
                    :checked="changecheckbox(item)"
                    >{{
                  }}</el-checkbox> -->
                    </div>
                    <div class="w-full">
                      <header
                        class="flex items-center justify-between border-b-solid border-1 border-gray-200 leading-10 text-base"
                      >
                        <div
                          class="font-black align-middle max-w-16/24 truncate"
                        >
                          {{ item.customerName }}
                        </div>
                        <div class="text-gray-400">
                          <el-icon class="align-middle"><Clock /></el-icon>
                          <span class="align-middle">
                            {{ item.createTime }}</span
                          >
                        </div>
                      </header>
                      <div class="content text-base">
                        <!-- <p class="my-2">
                      <span class="content-lable">客户名称</span>：{{
                        item.customerName
                      }}
                    </p> -->
                        <p class="my-2">
                          <span class="content-lable">税号</span>：{{
                            item.customerTaxcode
                          }}
                          <span
                            v-if="item.customerType"
                            class="float-right p-1 border-solid border-1 border-sky-400 rounded-md text-sky text-xs"
                            >{{ item.customerType }}</span
                          >
                        </p>
                        <p class="my-2">
                          <span class="content-lable">联系人</span>：{{
                            item.mainContactName
                          }}
                          <!-- <span v-if="item.mainContactPhone"
                            >/{{ item.mainContactPhone }}</span
                          > -->
                        </p>
                      </div>
                    </div>
                  </div>
                  <div
                    class="text-center p-6 border-solid border-1 border-slate-200 mb-6"
                    v-if="customerList.length == 0"
                  >
                    <div>
                      <span
                        class="i-line-md-coffee-half-empty-twotone-loop text-3xl text-gray-300"
                      ></span>
                    </div>
                    暂无记录
                  </div>
                </div>
              </div>

              <pagination
                v-show="customerTotal > 0"
                :total="customerTotal"
                :pager-count="5"
                :small="true"
                :autoScroll="false"
                :background="false"
                layout="total, prev, pager, next, jumper"
                v-model:page="customerQuery.pageNum"
                v-model:limit="customerQuery.pageSize"
                @pagination="getCustomerList"
              />
            </div>

            <div v-show="tabVal == 'cusLink'">
              <!-- <el-select
              v-show="tabVal == 'cusLink'"
              v-model="cusLinkId"
              placeholder="请输入个人客户名称选择个人客户"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              filterable
              remote
              :multiple="dialogObj.multiple"
              :checkStrictly="dialogObj.checkStrictly"
              :remote-method="val => queryContacts(val)"
              :loading="loadingSelect"
              no-data-text="未查询到个人客户"
            >
              <el-option
                v-for="item in contactsOptions"
                :key="item.id"
                :label="item.contactName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.contactName }}</span>
                  <span v-if="item.contactNumber"
                    >({{ item.contactNumber }})</span
                  >
                </div>
              </el-option>
            </el-select> -->
              <el-tabs
                v-model="cusLinkQuery.customerCondition"
                class="text-base"
              >
                <el-tab-pane
                  v-for="(item, index) in customer_condition"
                  :key="index"
                  :label="item.label"
                  :name="item.value"
                />
              </el-tabs>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-input
                    size="small"
                    v-model="cusLinkQuery.contactName"
                    class="w-full"
                    placeholder="客户名称"
                    :prefix-icon="'Search'"
                    clearable
                    @change="getCusLinkList"
                  />
                </el-col>
                <el-col :span="8">
                  <el-input
                    size="small"
                    v-model="cusLinkQuery.contactNumber"
                    class="w-full"
                    placeholder="联系手机"
                    :prefix-icon="'Search'"
                    clearable
                    @change="getCusLinkList"
                  />
                </el-col>
                <el-col :span="8">
                  <el-select
                    size="small"
                    class="w-full"
                    v-model="cusLinkQuery.contactType"
                    placeholder="选择客户类别"
                    clearable
                    @change="getCusLinkList"
                  >
                    <el-option
                      v-for="(dict, index) in contacts_class"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <div class="list mt-6" v-loading="loading.cusLink">
                <div class="overflow-y-auto" id="cusLinkBox">
                  <div
                    v-for="(item, index) in cusLinkList"
                    :key="index"
                    :class="[
                      'list-row',
                      'cursor-pointer',
                      'border-solid',
                      'border-1',
                      'border-gray-200',
                      'px-4',
                      'pb-4',
                      'flex',
                      'items-center',
                      'shadow-md',
                      'mb-4',
                      rowCalss(item)
                    ]"
                    @click="clickRow(item)"
                  >
                    <!-- <div>
                  <el-checkbox
                    v-model="item.checkbox"
                    :name="selectData"
                    @change="changecheckbox"
                    >{{
                  }}</el-checkbox>
                </div> -->
                    <div class="w-full">
                      <header
                        class="flex items-center justify-between border-b-solid border-1 border-gray-200 leading-10 text-base"
                      >
                        <div
                          class="font-black align-middle max-w-16/24 truncate"
                        >
                          {{ item.contactName }}
                        </div>
                        <div class="text-gray-400">
                          <el-icon class="align-middle"><Clock /></el-icon>
                          <span class="align-middle">
                            {{ item.createTime }}</span
                          >
                        </div>
                      </header>
                      <div class="content text-base">
                        <!-- <p class="my-2">
                      <span class="content-lable">客户姓名</span>：{{
                        item.contactName
                      }}
                    </p> -->
                        <p class="my-2">
                          <span class="content-lable">身份证编号</span>：{{
                            item.idNumber
                          }}
                          <span
                            v-if="item.contactType"
                            class="float-right p-1 border-solid border-1 border-sky-400 rounded-md text-sky text-xs"
                            >{{ item.contactType }}</span
                          >
                        </p>
                        <!-- <p class="my-2">
                          <span class="content-lable">联系方式</span>：{{
                            item.contactNumber
                          }}
                        </p> -->
                      </div>
                    </div>
                  </div>
                  <div
                    class="text-center p-6 border-solid border-1 border-slate-200 mb-6"
                    v-if="customerList.length == 0"
                  >
                    <div>
                      <span
                        class="i-line-md-coffee-half-empty-twotone-loop text-3xl text-gray-300"
                      ></span>
                    </div>
                    暂无记录
                  </div>
                </div>
              </div>

              <pagination
                v-show="cusLinkTotal > 0"
                :total="cusLinkTotal"
                :pager-count="5"
                :small="true"
                :autoScroll="false"
                :background="false"
                layout="total, prev, pager, next, jumper"
                v-model:page="cusLinkQuery.pageNum"
                v-model:limit="cusLinkQuery.pageSize"
                @pagination="getCusLinkList"
              />
            </div>

            <div v-show="tabVal == 'supplier'" class="pt-4">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-input
                    size="small"
                    v-model="supplierQuery.supplierName"
                    class="w-full"
                    placeholder="供应商名称"
                    :prefix-icon="'Search'"
                    clearable
                    @change="getSupplierList"
                  />
                </el-col>
              </el-row>
              <div class="list mt-6" v-loading="loading.supplier">
                <div class="overflow-y-auto" id="supplierBox">
                  <div
                    v-for="(item, index) in supplierList"
                    :key="index"
                    :class="[
                      'list-row',
                      'cursor-pointer',
                      'border-solid',
                      'border-1',
                      'border-gray-200',
                      'p-4',
                      'flex',
                      'items-center',
                      'shadow-md',
                      'mb-4',
                      rowCalss(item)
                    ]"
                    @click="clickRow(item)"
                  >
                    <!-- <div>
                  <el-checkbox
                    v-model="item.checkbox"
                    :name="selectData"
                    @change="changecheckbox"
                    >{{
                  }}</el-checkbox>
                </div> -->
                    <div class="w-full">
                      <header
                        class="flex items-center justify-between leading-10 text-base"
                      >
                        <div
                          class="font-black align-middle max-w-16/24 truncate"
                        >
                          {{ item.supplierName }}
                          <span v-if="item.supplierTaxcode"
                            >({{ item.supplierTaxcode }})</span
                          >
                        </div>
                        <div class="text-gray-400">
                          <dict-drop
                            :options="customer_star"
                            :value="item.starRating"
                          />
                        </div>
                      </header>
                    </div>
                  </div>
                  <div
                    class="text-center p-6 border-solid border-1 border-slate-200 mb-6"
                    v-if="supplierList.length == 0"
                  >
                    <div>
                      <span
                        class="i-line-md-coffee-half-empty-twotone-loop text-3xl text-gray-300"
                      ></span>
                    </div>
                    暂无记录
                  </div>
                </div>
              </div>

              <pagination
                v-show="supplierTotal > 0"
                :total="supplierTotal"
                :pager-count="5"
                :small="true"
                :autoScroll="false"
                :background="false"
                layout="total, prev, pager, next, jumper"
                v-model:page="supplierQuery.pageNum"
                v-model:limit="supplierQuery.pageSize"
                @pagination="getSupplierList"
              />

              <!-- <el-select
              v-show="tabVal == 'supplier'"
              v-model="supplierId"
              placeholder="请输入供应商名称选择供应商"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              filterable
              remote
              :multiple="dialogObj.multiple"
              :checkStrictly="dialogObj.checkStrictly"
              :remote-method="val => querySupplier(val)"
              :loading="loadingSelect"
              no-data-text="未查询到供应商"
            >
              <el-option
                v-for="item in supplierOptions"
                :key="item.id"
                :label="item.supplierName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.supplierName }}</span>
                  <span v-if="item.supplierNumber"
                    >({{ item.supplierNumber }})</span
                  >
                </div>
              </el-option>
            </el-select> -->
            </div>

            <!-- <el-select
            v-show="tabVal == 'inner'"
            v-model="innerId"
            ref="selectRef"
            class="w-full"
            popper-class="block"
            placeholder="选择内部单位"
          >
            <el-option
              v-for="item in companyOption"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select> -->
            <el-tree
              class="mt-6"
              v-show="tabVal == 'inner'"
              ref="treeRef"
              :data="companyTreeOption"
              node-key="id"
              default-expand-all
              show-checkbox
              :check-strictly="dialogObj.checkStrictly"
              :class="dialogObj.multiple ? '' : 'customNodeClass'"
              :check-on-click-node="true"
              @check-change="nodeClick"
              :default-checked-keys="
                Array.isArray(innerId) ? innerId : [innerId]
              "
            >
            </el-tree>
          </el-col>
          <!-- 
          v-if="props.dialogParam.multiple" -->
          <el-col
            :span="8"
            class="dialog-style-right"
            v-if="props.dialogParam.multiple"
          >
            <el-row>
              <el-col :span="18">已选</el-col>
              <el-col :span="6" class="clear" @click="handleClear()"
                >清空</el-col
              >
            </el-row>
            <ul class="dialog-style-list">
              <li
                v-for="item in selectData"
                :key="item.value"
                @click="!item.disabled ? handleDel(item) : ''"
              >
                {{ item.label }}
                <span v-if="!item.disabled">×</span>
              </li>
            </ul>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            @click="addCustomer"
            v-if="tabVal == 'customer' || tabVal == 'cusLink'"
            >新增</el-button
          >
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleAffirm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="custDia.open"
      :title="custDia.title"
      :destroy-on-close="true"
    >
      <div v-if="tabVal == 'customer'">
        <el-form
          :model="formCustParams"
          :rules="rulesCustForm"
          label-width="110px"
          ref="formCustRef"
        >
          <el-row :span="24">
            <el-col :span="11">
              <el-form-item
                label="企业名称："
                prop="bizCustomerAddDto.customerName"
              >
                <el-input
                  v-model="formCustParams.bizCustomerAddDto.customerName"
                  placeholder="填写企业名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="客户类别："
                prop="bizCustomerAddDto.customerType"
              >
                <!-- 客户类别 -->
                <el-select
                  class="w-full"
                  v-model="formCustParams.bizCustomerAddDto.customerType"
                  placeholder="客户类别"
                  multiple
                >
                  <el-option
                    v-for="(dict, index) in customer_class"
                    :key="index"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="业务分类"
                prop="bizCustomerAddDto.businessTypeArr"
              >
                <el-tree-select
                  style="width: 100%"
                  v-model="formCustParams.bizCustomerAddDto.businessTypeArr"
                  :data="userBusinessTypeOption"
                  :multiple="true"
                  :check-strictly="false"
                  :show-checkbox="true"
                  placeholder="请选择业务分类"
                />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="联系人："
                prop="bizCustomerAddDto.mainContactName"
              >
                <el-input
                  v-model="formCustParams.bizCustomerAddDto.mainContactName"
                  placeholder="填写联系人姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="联系电话："
                prop="bizCustomerAddDto.mainContactPhone"
              >
                <el-input
                  v-model="formCustParams.bizCustomerAddDto.mainContactPhone"
                  placeholder="填写联系电话"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="企业税号："
                prop="bizCustomerAddDto.customerTaxcode"
              >
                <el-input
                  maxlength="20"
                  v-model="formCustParams.bizCustomerAddDto.customerTaxcode"
                  placeholder="填写企业税号"
                  @blur="checkTaxcode"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="纳税人性质："
                prop="bizCustomerAddDto.taxNature"
              >
                <el-select
                  class="w-full"
                  v-model="formCustParams.bizCustomerAddDto.taxNature"
                  placeholder="请选择纳税人性质"
                >
                  <el-option
                    v-for="(dict, index) in tax_grade"
                    :key="index"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="客户等级："
                prop="bizCustomerAddDto.customerLevel"
              >
                <el-select
                  v-model="formCustParams.bizCustomerAddDto.customerLevel"
                  placeholder="请选择客户等级"
                  class="w-full"
                >
                  <el-option
                    v-for="(item, index) in customer_level"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="归属公司："
                required
                prop="bizCustomerAddDto.orgId"
              >
                <el-tree-select
                  style="width: 100%"
                  v-model="formCustParams.bizCustomerAddDto.orgId"
                  :data="companyOptions"
                  :props="{
                    value: 'id',
                    label: 'label',
                    children: 'children'
                  }"
                  placeholder="请选择归属公司"
                  value-key="id"
                  filterable
                  :disabled="userStore.user.orgId != '484'"
                  @change="orgChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="归属人员：" prop="bizCustomerAddDto.userId">
                <el-select
                  v-model="formCustParams.bizCustomerAddDto.userId"
                  placeholder="请选择归属人员"
                  @focus="userInputFocus"
                  class="w-full"
                >
                  <el-option
                    v-for="(item, index) in selectOptionObj['userId']"
                    :key="index"
                    :label="item.label"
                    :value="item.uuid"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div v-if="tabVal == 'cusLink'">
        <el-form
          :model="formCusLParams"
          :rules="rulesCusLForm"
          label-width="110px"
          ref="formCusLRef"
        >
          <el-row :span="24">
            <el-col :span="11">
              <el-form-item label="姓名：" prop="co.contactName">
                <el-input
                  v-model="formCusLParams.co.contactName"
                  placeholder="填写姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="类别：" required prop="co.contactType">
                <!-- 客户类别 -->
                <el-select
                  class="w-full"
                  v-model="formCusLParams.co.contactType"
                  placeholder="类别"
                >
                  <el-option
                    v-for="(dict, index) in contacts_class"
                    :key="index"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="业务分类" prop="co.businessTypeArr">
                <el-tree-select
                  style="width: 100%"
                  v-model="formCusLParams.co.businessTypeArr"
                  :data="userBusinessTypeOption"
                  :multiple="true"
                  :check-strictly="false"
                  :show-checkbox="true"
                  placeholder="请选择业务分类"
                />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="联系电话：" prop="co.contactNumber">
                <el-input
                  v-model="formCusLParams.co.contactNumber"
                  placeholder="填写联系电话"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="归属公司：" required>
                <el-tree-select
                  style="width: 100%"
                  v-model="formCusLParams.co.orgId"
                  :data="companyOptions"
                  :props="{
                    value: 'id',
                    label: 'label',
                    children: 'children'
                  }"
                  placeholder="请选择归属公司"
                  value-key="id"
                  filterable
                />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="销售经理：" required>
                <el-select
                  v-model="formCusLParams.co.userId"
                  placeholder="请选择销售经理"
                  @focus="userInputFocus"
                  class="w-full"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in selectOptionObj['userId']"
                    :key="index"
                    :label="item.label"
                    :value="item.uuid"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="custDia.open = false">取消</el-button>
          <el-button type="primary" @click="saveForm" :loading="btnLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="perDia"
      @ok="selectDialogData"
      @close="
        val => {
          perDia.isDialog = false
        }
      "
    ></SelectDialog>
  </div>
</template>

<script setup name="SelectCustomer">
import { ElTree } from 'element-plus'
import {
  createCustomer,
  getListByCustomerName,
  getListByCustomer,
  getDetailTactPage,
  getDetailTactlistByCactName,
  checkCustomerTaxCode
} from '@/api/customerManage/customerList'
import { createContact } from '@/api/customerManage/contactList'
import {
  listBySupplierrName,
  listBySupplier
} from '@/api/sourceModules/supplier'
import { useDict } from '@/utils/dict'
import { strToArr, getUniqueUserId, getTreeNodeByParam } from '@/utils/commo'
import { listDept } from '@/api/system/dept'
import { validatePhoneTwo } from '@/utils/validate'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { treeselectNoPriv } from '@/api/rsgl/zzjg'
import {
  userBusinessTypeOption //用户业务类型树
} from '@/hooks/dict/order'

// 通用数据store
const commonStore = useCommonStore()
const userStore = useUserStore()
const { proxy } = getCurrentInstance()

const {
  bidding_unit,
  customer_condition,
  customer_class,
  contacts_class,
  customer_star,
  tax_grade,
  customer_level
} = useDict(
  'bidding_unit',
  'customer_condition', //客户筛选条件
  'customer_class', //客户类别
  'contacts_class', //联系人类别
  'customer_star', //客户星级
  'tax_grade', //纳税人性质
  'customer_level' //客户等级
)

// 接受父级传递的参数
const props = defineProps({
  dialogParam: {
    required: true,
    type: Object || Array,
    default: () => {
      return {}
    }
  }
})
// loading等待加载
const loading = ref({
  customer: false,
  supplier: false,
  cusLink: false,
  inner: false
})
// 企业客户值
const customerId = ref()
// 个人客户值
const cusLinkId = ref()
// 供应商id
const supplierId = ref()
// 内部单位值
const innerId = ref()
/***公司树 数据*/
const companyTreeOption = ref([])
/***公司非树 数据*/
const companyOption = ref([])

// tab 选项值
const tabVal = ref('customer')
// tab 的配置项
const tabList = ref([
  {
    label: '企业客户',
    name: 'customer'
  },
  {
    label: '供应商',
    name: 'supplier'
  },
  {
    label: '个人客户',
    name: 'cusLink'
  },
  {
    label: '内部单位',
    name: 'inner'
  }
])
// 计算tab项的宽度
const radioBtnWidth = ref(
  computed(() => {
    let tabArr = tabList.value
    return `${100 / tabArr.length}%`
  })
)

const treeRef = ref(ElTree)
// 选中的数据
const selectData = ref([])
// 弹出框是否隐藏
const dialogVisible = ref(false)
const data = reactive({
  customerTotal: 0,
  customerQuery: {
    pageNum: 1,
    pageSize: 10,
    customerCondition: '1', //客户筛选条件
    customer: undefined, //客户名称
    customerType: undefined, //客户类型
    customerTaxcode: undefined //客户税号
  },
  customerList: [],
  cusLinkTotal: 0,
  cusLinkQuery: {
    pageNum: 1,
    pageSize: 10,
    customerCondition: '1', //客户筛选条件
    contactName: undefined, //名称
    contactNumber: undefined /* 联系电话 */,
    contactType: undefined //联系人类别
  },
  cusLinkList: [],
  supplierTotal: 0,
  supplierQuery: {
    pageNum: 1,
    pageSize: 10,
    supplierName: undefined
  },
  supplierList: [],
  perDia: {
    //人员弹窗
    isDialog: false
  },
  selectOptionObj: {},
  custDia: {
    //新增弹窗
    open: false,
    title: '新增客户'
  },
  companyOptions: [],
  formCustParams: {
    bizCustomerAddDto: {
      origin: '9',
      customerType: ['3'],
      businessTypeArr: [],
      customerLevel: '4'
    }, //客户信息
    bizCustomerExtDto: {}, //客户附加信息
    bizContactDto: {
      sex: '2'
    }, //联系人信息
    bizCustomerInvinfoDto: {
      invoiceType: '1',
      headerType: '1',
      invContentType: '1'
    }, //开票信息
    bizContactExtDto: {}, //联系人扩展信息
    co: {}
  }, //客户数据
  btnLoading: false,
  rulesCustForm: {
    // 企业名称
    'bizCustomerAddDto.customerName': [
      { required: true, message: '请输入企业名称', trigger: 'blur' }
    ],
    // 客户类别
    'bizCustomerAddDto.customerType': [
      { required: true, message: '请选择客户类别', trigger: 'change' }
    ],
    // 业务分类
    'bizCustomerAddDto.businessTypeArr': [
      { required: true, message: '请选择业务分类', trigger: 'change' }
    ],
    // 联系人
    'bizCustomerAddDto.mainContactName': [
      { required: true, message: '请输入联系人姓名', trigger: 'blur' }
    ],
    // 归属人员
    'bizCustomerAddDto.userId': [
      { required: true, message: '请选择归属人员', trigger: 'change' }
    ],
    // 客户等级
    'bizCustomerAddDto.customerLevel': [
      { required: true, message: '请选择客户等级', trigger: 'change' }
    ],
    // 联系人电话
    'bizCustomerAddDto.mainContactPhone': [
      { required: true, validator: validatePhoneTwo, trigger: 'blur' }
    ],
    //企业名称
    // 'bizCustomerInvinfoDto.taxName': [
    //   { required: true, message: '请输入企业名称', trigger: 'change' }
    // ],
    //企业税号
    'bizCustomerAddDto.customerTaxcode': [
      { required: true, message: '请输入企业税号', trigger: 'blur' }
    ],
    'bizCustomerAddDto.taxNature': [
      { required: true, message: '请选择纳税人性质', trigger: 'change' }
    ]
  },
  formCusLParams: {
    co: {
      contactType: '1',
      origin: '9',
      businessTypeArr: []
    },
    eo: {
      cultivateIndus: '1',
      isTwentyfive: 'Y'
    }
  },
  rulesCusLForm: {
    // 联系人姓名
    'co.contactName': [
      { required: true, message: '请输入联系人名称', trigger: 'blur' }
    ],
    'co.contactNumber': [
      { required: true, validator: validatePhoneTwo, trigger: 'blur' }
    ],
    // 业务分类
    'co.businessTypeArr': [
      { required: true, message: '请选择业务分类', trigger: 'change' }
    ]
  }
})
let {
  customerTotal,
  customerQuery,
  customerList,
  cusLinkTotal,
  cusLinkQuery,
  cusLinkList,
  supplierTotal,
  supplierQuery,
  supplierList,
  perDia,
  selectOptionObj,
  custDia,
  companyOptions,
  formCustParams,
  btnLoading,
  rulesCustForm,
  formCusLParams,
  rulesCusLForm
} = toRefs(data)
//设置参数
const dialogObj = reactive({
  // avue-tree 的数据
  multiple: false, //是否多选
  checkStrictly: false, //是否遵循父子不互相关联的做法，默认为 false
  nodeKey: props.dialogParam.nodeKey || 'id', //值默认id
  defaultCheckedKeys: [], //默认选中的值key
  defaultCheckedLabel: [], //默认选中值得Label
  tabShow: true,
  tabVal: tabVal.value, //tab的默认值
  tabList: [
    // {
    //   label: '供应商',
    //   name: 'supplier'
    // },
    {
      label: '企业客户',
      name: 'customer'
    },
    {
      label: '个人客户',
      name: 'cusLink'
    }
    // {
    //   label: '内部单位',
    //   name: 'inner'
    // }
  ]
})
watch(
  customerId,
  val => {
    // console.log('选择客户==》', val)
    if (Array.isArray(val)) {
      let arr = []
      val.forEach(e => {
        parentOptions.value.forEach(item => {
          item.id === e ? arr.push({ ...item }) : ''
        })
      })
      selectData.value = arr.map(item => {
        return {
          ...item,
          value: item.id,
          label: item.customerName
        }
      })
    } else {
      let choose = parentOptions.value.filter(item => item.id === val)
      if (choose.length && val) {
        selectData.value = [
          {
            ...choose[0],
            value: choose[0].id,
            label: choose[0].customerName
          }
        ]
      } else if (!val) {
        selectData.value = []
      }
    }
  },
  { deep: true }
)
watch(
  cusLinkId,
  val => {
    // console.log('选择个人客户==》', val)
    if (Array.isArray(val)) {
      let arr = []
      val.forEach(e => {
        contactsOptions.value.forEach(item => {
          item.id === e ? arr.push({ ...item }) : ''
        })
      })
      selectData.value = arr.map(item => {
        return {
          ...item,
          value: item.id,
          label: item.contactName
        }
      })
    } else {
      let choose = contactsOptions.value.filter(item => item.id === val)
      if (choose.length && val) {
        selectData.value = [
          {
            ...choose[0],
            value: choose[0].id,
            label: choose[0].contactName
          }
        ]
      } else if (!val) {
        selectData.value = []
      }
    }
  },
  { deep: true }
)
watch(
  supplierId,
  val => {
    // console.log('选择供应商==》', val)
    if (Array.isArray(val)) {
      let arr = []
      val.forEach(e => {
        supplierOptions.value.forEach(item => {
          item.id === e ? arr.push({ ...item }) : ''
        })
      })
      selectData.value = arr.map(item => {
        return {
          ...item,
          value: item.id,
          label: item.supplierName
        }
      })
    } else {
      let choose = supplierOptions.value.filter(item => item.id === val)
      if (choose.length && val) {
        selectData.value = [
          {
            ...choose[0],
            value: choose[0].id,
            label: choose[0].supplierName
          }
        ]
      } else if (!val) {
        selectData.value = []
      }
    }
  },
  { deep: true }
)
watch(
  innerId,
  async val => {
    // console.log('选择内部单位==》', val)
    // console.log('选择内部单位companyOption.value==》', companyOption.value)
    if (Array.isArray(val)) {
      let arr = []
      val.forEach(e => {
        companyOption.value.forEach(item => {
          item.id === e ? arr.push({ ...item }) : ''
        })
      })
      selectData.value = arr.map(item => {
        return {
          ...item,
          value: item.id,
          label: item.label
        }
      })
      proxy.$nextTick(() => {
        treeRef.value.setCheckedKeys(val)
      })
    } else {
      let choose = companyOption.value.filter(item => item.id === val)
      if (choose.length && val) {
        selectData.value = [
          {
            ...choose[0],
            value: choose[0].id,
            label: choose[0].label
          }
        ]
        // treeRef.value.setCheckedKeys([val])
      } else if (!val) {
        selectData.value = []
        proxy.$nextTick(() => {
          treeRef.value.setCheckedKeys([])
        })
      }
    }
  },
  { deep: true }
)
watch(
  [
    () => customerQuery.value.customerCondition,
    () => cusLinkQuery.value.customerCondition
  ],
  (newVal, oleVal) => {
    newVal[0] !== oleVal[0] ? getCustomerList() : ''
    newVal[1] !== oleVal[1] ? getCusLinkList() : ''
  }
)

// 初始化
watch(
  () => props.dialogParam,
  async () => {
    dialogVisible.value = props.dialogParam.isDialog // 表单弹出框
    dialogObj.defaultCheckedKeys = props.dialogParam.defaultCheckedKeys
    // dialogObj.defaultCheckedLabel = props.dialogParam.defaultCheckedLabel
    //获取tree数据
    dialogObj.multiple = props.dialogParam.multiple //是否多选
    dialogObj.checkStrictly = props.dialogParam.checkStrictly //是否遵循父子不互相关联的做法
    dialogObj.nodeKey = props.dialogParam.nodeKey

    // 判断是否显示tab栏
    if (
      props.dialogParam.tabShow !== '' &&
      props.dialogParam.tabShow !== null &&
      props.dialogParam.tabShow !== undefined
    ) {
      dialogObj.tabShow = props.dialogParam.tabShow
    } else {
      dialogObj.tabShow = true
    }
    tabVal.value = props.dialogParam.tabVal
      ? props.dialogParam.tabVal
      : 'customer' //tab赋值
    tabList.value = props.dialogParam.tabList
      ? props.dialogParam.tabList
      : dialogObj.tabList //tab配置赋值

    if (props.dialogParam.multiple) {
      dialogObj.defaultCheckedKeys = strToArr(
        props.dialogParam.defaultCheckedKeys
      )
      // dialogObj.defaultCheckedLabel = strToArr(
      //   props.dialogParam.defaultCheckedLabel
      // )
    }
    // 弹窗回填
    if (props.dialogParam.tabVal == 'customer') {
      await queryCustomer(
        dialogObj.defaultCheckedKeys
          ? dialogObj.defaultCheckedKeys.toString()
          : undefined
      )
      customerId.value = dialogObj.defaultCheckedKeys
    } else if (props.dialogParam.tabVal == 'cusLink') {
      await queryContacts(
        dialogObj.defaultCheckedKeys
          ? dialogObj.defaultCheckedKeys.toString()
          : undefined
      )
      cusLinkId.value = dialogObj.defaultCheckedKeys
    } else if (props.dialogParam.tabVal == 'supplier') {
      await querySupplier(
        dialogObj.defaultCheckedKeys
          ? dialogObj.defaultCheckedKeys.toString()
          : undefined
      )
      supplierId.value = dialogObj.defaultCheckedKeys
    } else if (props.dialogParam.tabVal == 'inner') {
      innerId.value = dialogObj.defaultCheckedKeys
    }
  },
  {
    // flush: 'post'
    immediate: true,
    deep: true
  }
)

/**
 *切换客户类型时
 * @param {String} val 企业客户:customer;供应商:supplier;个人客户:cusLink;内部单位:inner
 */
function changeTab(val) {
  // console.log('切换客户类型==》', val)
  if (props.dialogParam.multiple) {
    customerId.value = []
    cusLinkId.value = []
    supplierId.value = []
    innerId.value = []
    selectData.value = []
  }
}
// 选中行样式
const rowCalss = computed(() => {
  return function (row) {
    let select = selectData.value.filter(e => e.id == row.id)
    return select.length > 0 ? 'bg-blue-50' : ''
  }
})
// 选中行图标样式
const checkIcon = computed(() => {
  return function (row) {
    let select = selectData.value.filter(e => e.id == row.id)
    return select.length > 0
      ? 'i-ic-baseline-check-box text-blue-500'
      : 'i-ic-round-check-box-outline-blank'
  }
})
// 滚动条回到顶部
function initScroll(id) {
  proxy.$nextTick(() => {
    let dom = document.getElementById(id)
    if (dom !== null) {
      dom.scrollTop = 0
    }
  })
}

/* 获取企业客户列表 */
async function getCustomerList() {
  loading.value.customer = true
  initScroll('customerBox')
  let res = await getListByCustomer(customerQuery.value)
  loading.value.customer = false
  if (res.code !== 200) return
  customerList.value = res.rows
  customerTotal.value = res.total
  // console.log(res, 'res')
}
/* 获取个人客户列表 */
async function getCusLinkList() {
  loading.value.cusLink = true
  initScroll('cusLinkBox')
  let res = await getDetailTactPage(cusLinkQuery.value)
  loading.value.cusLink = false
  if (res.code !== 200) return
  cusLinkList.value = res.rows
  cusLinkTotal.value = res.total
  // console.log(res, 'res')
}
/* 获取供应商列表 */
async function getSupplierList() {
  loading.value.supplier = true
  initScroll('supplierBox')
  let res = await listBySupplier(supplierQuery.value)
  loading.value.supplier = false
  if (res.code !== 200) return
  supplierList.value = res.rows
  supplierTotal.value = res.total
  // console.log(res, 'res')
}
// 点击行
function clickRow(row) {
  let select = selectData.value.filter(e => e.id == row.id) //判断点击的数据是否在列表中
  if (tabVal.value == 'customer') {
    let contain = []
    contain = parentOptions.value.filter(val => val.id == row.id)
    contain.length == 0 ? parentOptions.value.push({ ...row }) : ''
    if (!dialogObj.multiple) {
      customerId.value = ''
      customerId.value = select.length > 0 ? '' : row.id
    } else {
      select.length == 0
        ? customerId.value.push(row.id)
        : customerId.value.splice(customerId.value.indexOf(row.id), 1)
    }
  } else if (tabVal.value == 'cusLink') {
    let contain = []
    contain = contactsOptions.value.filter(val => val.id == row.id)
    contain.length == 0 ? contactsOptions.value.push({ ...row }) : ''
    if (!dialogObj.multiple) {
      cusLinkId.value = ''
      cusLinkId.value = select.length > 0 ? '' : row.id
    } else {
      select.length == 0
        ? cusLinkId.value.push(row.id)
        : cusLinkId.value.splice(cusLinkId.value.indexOf(row.id), 1)
    }
  } else if (tabVal.value == 'supplier') {
    let contain = []
    contain = supplierOptions.value.filter(val => val.id == row.id)
    contain.length == 0 ? supplierOptions.value.push({ ...row }) : ''
    if (!dialogObj.multiple) {
      supplierId.value = ''
      supplierId.value = select.length > 0 ? '' : row.id
    } else {
      select.length == 0
        ? supplierId.value.push(row.id)
        : supplierId.value.splice(supplierId.value.indexOf(row.id), 1)
    }
  } else if (tabVal.value == 'inner') {
    console.log('内部')
  }
}
/***所属企业/客户名称数据 start*/
const parentOptions = ref([]) //所属企业/客户名称数据
/**
 * 所属企业模糊搜索
 * @param val 当前输入的值
 */
async function queryCustomer(val) {
  if (!val) {
    return
  }
  // console.log('客户名称val==>', val)
  let params = {
    pageSize: 10,
    // customer: val,
    ids: val
  }
  await getListByCustomerName(params).then(res => {
    parentOptions.value = res.data
    // console.log(parentOptions.value, 'parentOptions.value ')
  })
}
/***客户联系人数据  start*/
const contactsOptions = ref([])
/**
 * 客户联系人模糊搜索
 * @param val 当前输入的值
 * @param entId 客户id
 * @param mes 错误提示信息
 */
async function queryContacts(val) {
  if (!val) {
    return
  }
  let params = {
    pageSize: 10,
    entId: '',
    // contactName: val,
    ids: val
  }
  await getDetailTactlistByCactName(params).then(res => {
    contactsOptions.value = res.data
  })
}
/***供应商名称数据 start*/
const supplierOptions = ref([]) //供应商数据
/**
 * 供应商模糊搜索
 * @param val 当前输入的值
 */
async function querySupplier(val) {
  if (!val) {
    return
  }
  let params = {
    pageSize: 10,
    // supplierName: val,
    ids: val
  }
  await listBySupplierrName(params).then(res => {
    supplierOptions.value = res.data
    console.log(supplierOptions.value, 'supplierOptions.value ')
  })
}

// 获取内部单位数据
async function getInnerCo() {
  // let res = await listDept({ deptType: 1 })
  console.log(bidding_unit.value, 'bidding_unit')
  let biddingUnit = toRaw(bidding_unit.value)
  companyOption.value = biddingUnit.map(e => {
    e.id = e.value
    return e
  })
  // proxy.handleTree(response, 'deptId')
  companyTreeOption.value = companyOption.value //proxy.handleTree(companyOption.value)
  // proxy.$refs.selectRef
}

// tree点击选中
const nodeClick = (data, checked) => {
  // console.log('data, checked', data, checked)
  if (!dialogObj.multiple) {
    if (checked) {
      dialogObj.defaultCheckedKeys = [data[dialogObj.nodeKey]]
      treeRef.value.setCheckedKeys([data[dialogObj.nodeKey]])
      // console.log('treeRef.value1', treeRef.value.getCheckedNodes())
    } else {
      if (
        dialogObj.defaultCheckedKeys &&
        dialogObj.defaultCheckedKeys[0] === data[dialogObj.nodeKey]
      ) {
        treeRef.value.setCheckedKeys([data[dialogObj.nodeKey]])
        // console.log('treeRef.value2', treeRef.value.getCheckedNodes())
      }
    }
    let sData = treeRef.value.getCheckedNodes() //获取选中的值
    sData.forEach(e => {
      innerId.value = e.id
    })
    selectData.value = sData
  }
}

const emit = defineEmits(['ok', 'close'])
// 确认操作
const handleAffirm = () => {
  let sData = [...selectData.value]
  let labelData = [],
    defaultCheckedKeys = []
  sData.forEach(item => {
    labelData.push(item.label)
    defaultCheckedKeys.push(item[dialogObj.nodeKey])
  })
  emit('ok', {
    ...props.dialogParam,
    type: props.dialogParam.type,
    tabVal: tabVal.value,
    selectData: sData,
    labelData: labelData, // 选中的数据label
    defaultCheckedKeys: defaultCheckedKeys, // 选中的数据id
    dialogVisible: false
  })
  reset()
}
// 取消操作
const handleCancel = () => {
  reset()
  emit('close')
}
// 删除选中数据
const handleDel = val => {
  clickRow(val)

  // if (Array.isArray(customerId.value)) {
  //   customerId.value = customerId.value.filter(item => item !== val.id)
  // } else {
  //   customerId.value = ''
  // }
  // if (Array.isArray(cusLinkId.value)) {
  //   cusLinkId.value = cusLinkId.value.filter(item => item !== val.id)
  // } else {
  //   cusLinkId.value = ''
  // }
  // if (Array.isArray(supplierId.value)) {
  //   supplierId.value = supplierId.value.filter(item => item !== val.id)
  // } else {
  //   supplierId.value = ''
  // }
  // if (Array.isArray(innerId.value)) {
  //   innerId.value = innerId.value.filter(item => item !== val.id)
  // } else {
  //   innerId.value = ''
  // }
  dialogObj.defaultCheckedKeys = []
}
// 清空数据
const handleClear = () => {
  console.log('清空数据')
  Array.isArray(customerId.value)
    ? (customerId.value = [])
    : (customerId.value = '')
  Array.isArray(cusLinkId.value)
    ? (cusLinkId.value = [])
    : (cusLinkId.value = '')
  Array.isArray(supplierId.value)
    ? (supplierId.value = [])
    : (supplierId.value = '')
  Array.isArray(innerId.value) ? (innerId.value = []) : (innerId.value = '')
  dialogObj.defaultCheckedKeys = []
}
const reset = () => {
  dialogVisible.value = false
  dialogObj.data = []
  selectData.value = []
  dialogObj.defaultCheckedKeys = []
}

// 新增客户
async function addCustomer() {
  await getCompany()
  await getDefaultUserInfo()
  if (tabVal.value == 'customer') {
    formCustParams.value.bizCustomerAddDto.orgId = userStore.user.orgId
    formCustParams.value.bizContactDto.orgId = userStore.user.orgId
  } else if (tabVal.value == 'cusLink') {
    formCusLParams.value.co.orgId = userStore.user.orgId
  }
  custDia.value.open = true
}
/**
 * 获取归属公司数据
 * @returns {Promise<void>}
 */
async function getCompany() {
  if (userStore.user.orgId !== 484) {
    // 所属单位列表
    commonStore.getCompanyData().then(data => {
      companyOptions.value = data
    })
  } else {
    //   无权限的所属公司
    let response = await treeselectNoPriv({ deptType: 1 })
    companyOptions.value = response.data
  }
}
/**
 * 根据当前用户回填归属人员表单
 */
async function getDefaultUserInfo(userId, orgId) {
  let id = ''
  if (userId) {
    id = userId
  } else {
    //获取当前用户id
    id = userStore.user.userId
  }
  //获取部门人员数据
  const deptUserData = await commonStore.getUseTreeData({ deptId: orgId })

  //根据当前用户id获取uuid
  let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
  selectOptionObj.value.userId = obj
  if (tabVal.value == 'customer') {
    formCustParams.value.bizCustomerAddDto.userId = obj[0].uuid
  } else if (tabVal.value == 'cusLink') {
    formCusLParams.value.co.userId = obj[0].uuid
  }
}
/**
 * 归属人员input获取焦点事件
 */
function userInputFocus() {
  console.log('===>')
  perDia.value = {
    type: 'userId',
    title: '请选择归属人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: false,
    checkStrictly: false
  }
  perDia.value.isDialog = true

  if (tabVal.value == 'customer') {
    perDia.value.defaultCheckedKeys =
      [formCustParams.value.bizCustomerAddDto.userId] || []
  } else if (tabVal.value == 'cusLink') {
    perDia.value.defaultCheckedKeys = [formCusLParams.value.co.userId] || []
  }
}
/** 弹出框下拉框
 * 项目负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'userId':
      console.log('选择人员==》', val)
      selectOptionObj.value['userId'] = val.selectData
      if (tabVal.value == 'customer') {
        formCustParams.value.bizCustomerAddDto.userName =
          val.labelData && val.labelData.length > 0 ? val.labelData[0] : null
        formCustParams.value.bizCustomerAddDto.userId =
          val.defaultCheckedKeys && val.defaultCheckedKeys.length > 0
            ? val.defaultCheckedKeys[0]
            : null
      } else if (tabVal.value == 'cusLink') {
        formCustParams.value.co.userName =
          val.labelData && val.labelData.length > 0 ? val.labelData[0] : null
        formCusLParams.value.co.userId =
          val.defaultCheckedKeys && val.defaultCheckedKeys.length > 0
            ? val.defaultCheckedKeys[0]
            : null
      }
      break
  }
}

/**
 * 失去焦点的时候校验税号
 * @param val
 */
const checkTaxcode = () => {
  return new Promise((resolve, reject) => {
    let isUniqueTaxCode = false
    let taxCode = formCustParams.value.bizCustomerAddDto.customerTaxcode
    // 新增
    checkCustomerTaxCode(taxCode)
      .then(res => {
        if (res.data != null) {
          proxy.$modal.msgError('已存在相同税号')
          return
        } else {
          isUniqueTaxCode = true
          resolve(isUniqueTaxCode)
        }
      })
      .finally(() => {
        reject()
      })
  })
}

const orgChange = val => {
  //归属人员清空
  formCustParams.value.bizCustomerAddDto.userId = ''
}
// 保存表单
function saveForm() {
  if (tabVal.value == 'customer') {
    proxy.$refs.formCustRef.validate(async (valid, fields) => {
      if (valid) {
        btnLoading.value = true
        let data = JSON.parse(JSON.stringify(toRaw(formCustParams.value)))
        if (formCustParams.value.bizCustomerAddDto.cityCode) {
          // 转换所在区域城市编码
          data.bizCustomerAddDto.cityCode =
            formCustParams.value.bizCustomerAddDto.cityCode.join(',')
        }
        if (formCustParams.value.bizCustomerAddDto.userId) {
          // 获取查询到的user数据对象
          let userObj = getUniqueUserId(
            selectOptionObj.value['userId'],
            formCustParams.value.bizCustomerAddDto.userId
          )
          //获取userid
          data.bizCustomerAddDto.userId = userObj.id
          data.bizContactDto.userId = userObj.id

          //获取deptId
          data.bizCustomerAddDto.deptId = userObj.deptId
          data.bizContactDto.deptId = userObj.deptId

          //   获取userName
          data.bizCustomerAddDto.userName = userObj.label
          data.bizContactDto.userName = userObj.label
        }
        //客户类别
        data.bizCustomerAddDto.customerType =
          data.bizCustomerAddDto.customerType.toString()

        checkTaxcode()
          .then(res => {
            // 新增
            createCustomer(data)
              .then(async res => {
                proxy.$modal.msgSuccess(res.msg)
                handleReset()
                // examineParam.value.businessId = res.data
                await getCustomerList()
                customerList.value.forEach(item => {
                  if (item.id == res.data) {
                    clickRow(item)
                  }
                })
                custDia.value.open = false
                btnLoading.value = false
                console.log('res.data==>', res.data)
              })
              .finally(() => {
                btnLoading.value = false
              })
          })
          .catch(() => {
            btnLoading.value = false
          })
      }
    })
  } else if (tabVal.value == 'cusLink') {
    proxy.$refs.formCusLRef.validate((valid, fields) => {
      if (valid) {
        btnLoading.value = true
        let data = JSON.parse(JSON.stringify(toRaw(formCusLParams.value)))
        if (formCusLParams.value.co.cityCode) {
          // 转换所在区域城市编码
          data.co.cityCode = formCusLParams.value.co.cityCode.join(',')
        }
        // 销售经理
        if (formCusLParams.value.co.userId) {
          // 获取查询到的user数据对象
          let userObj = getUniqueUserId(
            selectOptionObj.value['userId'],
            formCusLParams.value.co.userId
          )
          //获取userid
          data.co.userId = userObj.id

          //获取deptId
          data.co.deptId = userObj.deptId

          //   获取userName
          data.co.userName = userObj.label
        }
        data.co.entType = '1'
        // 判断联系人是否有所属企业 如果没有则设置为0
        if (!data.co.entId) {
          data.co.entId = '0'
        }
        //   新增联系人
        createContact(data)
          .then(async res => {
            proxy.$modal.msgSuccess(res.msg)
            handleReset()
            custDia.value.open = false
            await getCusLinkList()
            btnLoading.value = false
            cusLinkList.value.forEach(item => {
              if (item.id == res.data) {
                clickRow(item)
              }
            })
          })
          .finally(() => {
            btnLoading.value = false
          })
        // console.info('form.value', formCusLParams.value)
      }
    })
  }
}
// 清空表单
function handleReset() {
  if (tabVal.value == 'customer') {
    proxy.resetForm('formCustRef')
  } else if (tabVal.value == 'cusLink') {
    proxy.resetForm('formCusLRef')
  }
}
function init() {
  getInnerCo()
  getCustomerList()
  getCusLinkList()
  getSupplierList()
}
init()
</script>
<style scoped lang="scss">
.customer-dialog {
  ul,
  li {
    margin: 0;
    margin-block-end: 0;
    margin-block-start: 0;
  }
  .dialog-style {
    @apply mt--20px h-560px;
    overflow: auto;
    .dialog-style-left {
      border-right: 1px solid #ccc;
      :deep(.el-radio-button__inner) {
        @apply w-full;
      }
      @apply pr-20px;
      .customNodeClass {
        :deep(.el-checkbox__inner) {
          @apply rounded-50;
        }
      }
      :deep(.pagination-container) {
        position: relative;
      }
      .list {
        .content {
          .content-lable {
            @apply inline-block;
            min-width: 60px;
            text-align: justify;
            text-align-last: justify;
          }
        }
      }
    }
    .dialog-style-right {
      @apply leading-30px pl-20px;
      .clear {
        color: var(--el-color-primary);
        @apply text-right;
      }
    }
    .dialog-style-list {
      @apply mt-15px ml--40px  leading-20px;
      li {
        color: #999;
        background-color: #f5f5f5;
        @apply flex items-center list-none pl-15px pt-5px pb-5px mb-10px rounded-35px cursor-pointer;
        span {
          color: var(--el-color-primary);
          @apply flex-1 text-right pr-15px cursor-pointer;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.customer-dialog {
  .el-dialog__body {
    padding-bottom: 10px !important;
  }
}
</style>
